templatePath = 'template-path/'
angular.module('UCX.Cmis')
.controller 'directiveController',(
  $scope
  $http
  CmisService
  localStorageService
  $timeout
  $uibModal
  ModelService
  Loading
  Utils
  $translate
  $filter
  UploadQueue
  $rootScope
  $location
  ContextMenuService
  ApiService
  $sce
  $injector
)->
  
#    if readerPluginVersion >8.1 hide send by email func
  $scope.showSendEmail = false
  pluginVersion = CmisService.pluginVersion
  if(parseFloat(pluginVersion)>8.1)
    $scope.showSendEmail = true
  else
    $scope.showSendEmail = false
  if !window.CloudReading
    window.CloudReading={}
  window.CloudReading.Utils =Utils
  $scope.OS = Utils.getOsName()
  $scope.isIEorEdge = Utils.isIEorEdge()
  $scope.isSafari = Utils.isSafari()
  console.log 'iswin',$scope.isIEorEdge
##
#  all Jquery ajax call success or error handle
#
#    As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxSuccess() method, must be attached to document.
#    If $.ajax() or $.ajaxSetup() is called with the 'global' option set to false, the .ajaxSuccess() method will not fire.
#    global (default: true)
#    Type: Boolean
#    Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
##
  window.recordRequestTime ={
    start:{},
    end:{},
    cost:{}
  }


  $( document ).ajaxSuccess(( event, responseData, settings )->
#    console.log('settings',settings)
#    console.log('ajaxSuccess',responseData)
#    console.log('settings',settings)
#    success but error
    if responseData && responseData.responseJSON && responseData.responseJSON.message
      if responseData.responseJSON.message == 'TOKEN_ERROR'
        Utils.handleTokenError(responseData.responseJSON)
  )
  $( document ).ajaxError(( event, responseData, settings )->
#    console.log('settings',settings)
#    console.log('ajaxError',responseData)
    if responseData && responseData.responseJSON && responseData.responseJSON.message
      if responseData.responseJSON.message == 'TOKEN_ERROR'
        Utils.handleTokenError(responseData.responseJSON)
  )
  $( document ).ajaxSend((event,jqXHR,options)->
#    console.log(event)
#    console.log(jqXHR)
#    console.log(options)
#    console.log("ajaxSend")
    window.recordRequestTime.start[options.url]=Date.now()
  )
  $( document ).ajaxComplete((event,jqXHR,options)->
#    console.log(event)
#    console.log(jqXHR)
    console.log(options)
#    console.log("ajaxComplete")
    window.recordRequestTime.end[options.url]=Date.now()
    cost = window.recordRequestTime.end[options.url]-window.recordRequestTime.start[options.url]
    window.recordRequestTime.cost[options.url] = cost
    if(cost>2000)
      console.warn('cost',cost)
    else
      console.log('cost',cost)
  )


  $scope.templatePath = templatePath
  $scope.messageToMember = $filter('nl2br')(CmisService.messageToMember)
  $scope.showMembers = CmisService.showMembers
  $scope.roomLink = CmisService.roomLink
  $scope.membershipType = CmisService.membershipType
  $scope.supportFile = if typeof File != 'undefined' then true else false
  $scope.multipleChooseFiles = []
  $scope.fileListShow=false
  $scope.folderOrderBy = Utils.getSort()
  $scope.trStyle = Utils.getFileSort()
  $scope.repository = CmisService.repository
  $scope.device = CmisService.device
  $scope.fromFillAndSign = CmisService.fromFillAndSign
  $scope.isAndroid = CmisService.isAndroid
  $scope.isIOS = CmisService.isIOS
  $scope.filePickerModal=CmisService.filePickerModal
  $scope.lang = Utils.getLanguage()

  $scope.pluginUi=CmisService.pluginUi
  $scope.fileType=CmisService.fileType
  $scope.fileSelectMode=CmisService.fileSelectMode

#  console.log $scope.device
  $scope.changeSort = (sort)->

    if($scope.folderOrderBy == sort)
      if $scope.folderOrderBy.indexOf('-') != -1
        $scope.folderOrderBy = sort.slice(1)
      else
        $scope.folderOrderBy = '-'+sort
    else
      $scope.folderOrderBy = sort
    Utils.sendGaEvent('Document list','Sort by:'+$scope.folderOrderBy,$scope.folderOrderBy)
    localStorageService.set "folder-order-by" , $scope.folderOrderBy
  $scope.changeDocShowStyle=()->
    $scope.trStyle=!$scope.trStyle
    Utils.sendGaEvent('Document list','List style:'+$scope.trStyle,'List style or thumbnail style')
    localStorageService.set "file-order-by" , $scope.trStyle
  $scope.translateErrorMsg=Utils.translateErrorMsg


  CmisServiceSession = CmisService.session

  cancalCheckoutUploadNewversion = () ->
    console.log $scope.tempFile
    console.log $scope.tempFile.isVersionSeriesCheckedOut
    console.log Utils.isUploadNewVersioning
    if Utils.isUploadNewVersioning
      localStorageService.set "cancel-file-checkout" , $scope.tempFile.id

  window.onbeforeunload = (e) ->
    if Utils.isUploadNewVersioning == true
      cancalCheckoutUploadNewversion()
      return ''

#  $scope.$on(
#    '$locationChangeSuccess',
#    (e, newUrl, oldUrl)->
#      if $scope.progress != 100
#        return
#      if newUrl.substr(newUrl.lastIndexOf('#')) == -1
#        return
#      anchor = newUrl.substr(newUrl.lastIndexOf('#')+1)
#      if anchor.indexOf('file') == -1 && anchor.indexOf('search') == -1
#        localStorageService.set "lastAnchor" , anchor
#      $scope.doActionFromAnchor(anchor)
#  )
  $scope.$on(
    '$locationChangeSuccess',
    (e, newUrl, oldUrl)->
      if CmisService.isAndroid || CmisService.isIOS
        localStorageService.set "lastAnchor" , anchor
        return
      #      这个 地方的return 需要修改啊 不能这样 要等 progress == 100 之后再去 监听 url 变化
      if $scope.progress != 100
        return
      if newUrl.lastIndexOf('#') == -1
        if $scope.tree[0]
          console.log('oyeah')
          anchor = '/folder/'+$scope.tree[0]['id']
          $scope.doActionFromAnchor(anchor)
          return
        else
          console.log('ggggg')
          return
      anchor = newUrl.substr(newUrl.lastIndexOf('#')+1)
      if anchor.indexOf('file') ==-1 && anchor.indexOf('search') ==-1
        localStorageService.set "lastAnchor" , anchor
      $scope.doActionFromAnchor(anchor)
  )
  $scope.canMerge = (multipleFiles)->
    canMerge = false
    for file in multipleFiles
      if file.canPreviewLikePdf()
        canMerge = true
      else
        canMerge = false
        break
#    console.log('========can merge=======')
#    console.log(canMerge)
    return canMerge
  $scope.mergePdf = (multipleFiles,event)->
    if event
      event.preventDefault()
      event.stopPropagation()
    if $scope.disableMerge
      Utils.warning($translate.instant('merge_not_support_for_too_many'))
      return
    else
      console.log('========multipleFiles=======')
      console.log(multipleFiles)
      fileLinks = []
      fileName = []
      link = ''
      for file in multipleFiles
        fileLinks.push(file.getPreviewLink())
        fileName.push(file.name)
        link += '&fileurl[]='+encodeURIComponent(file.getPreviewLink())+'&filename[]='+encodeURIComponent(file.name)
      console.log('========fileLinks=======')
      console.log(fileLinks)
      console.log('========fileName=======')
      console.log(fileName)
      console.log('========link=======')
      console.log(link)

      targetUrl = CmisService.cwebToolsApi+'?al=en-US&mode=phantom-merge-pdf&access_token='+CmisService.token

      form = document.createElement('form')
      form.action = targetUrl
      form.method = 'post'
      form.style = "display: none;"
      form.target = "_blank"
      for item,key in fileName
        input = document.createElement("input")
        input.name = 'filename[]'
        input.value = fileName[key]

        input2 = document.createElement("input")
        input2.name = 'fileurl[]'
        input2.value = fileLinks[key]
        
        form.appendChild(input)
        form.appendChild(input2)

      console.log(form);
      $('body').append(form);
      $(form).submit();
      $(form).remove();

      return true
  $scope.organizePDFPage = (file)->
#    link = '&fileurl[]='+encodeURIComponent(file.getPreviewLink())+'&filename[]='+encodeURIComponent(file.name)
#    targetUrl = CmisService.cwebToolsApi+'?al=en-US&mode=phantom-page-organizer&access_token='+CmisService.token+link

    token = CmisService.token
    domain = CmisService.baseUrl.replace('cloud', 'pdfeditor') # https://pdfeditor-demo.connectedpdf.com/
    doc_preview_url = "/preview/cmis/"+file.id+"/"+encodeURIComponent("&viewermodel=1") # PPO mode
    targetUrl = domain+"login-integration/"+encodeURIComponent(doc_preview_url)+"/"+token

    console.log('========targetUrl =======')
    console.log(targetUrl)

    if CmisService.device == 'phantom-online' || CmisService.device == 'reader-online'
      window.parent.angularHeaderComponent.zone.run(()->
        window.parent.angularHeaderComponent.navigateByUrl(doc_preview_url)
      )
      return true;

    window.open(targetUrl)
    return true


  $scope.pdfPreview = (document)->
    if CmisService.isIOS
      $cordovaStatusbar = $injector.get('$cordovaStatusbar')
      $cordovaStatusbar.hide()
    $scope.iframePdf = true
    $scope.isOdfPreview=false
    $scope.isFullScreenPreview = false
    $scope.isNormalFilePreview=true
    url = CmisService.baseUrl+'doc/pdf-preview?objectid='+document.id + '&token=' + CmisService.token
    $http.get(CmisService.baseUrl + 'api/document/get-doc-preview-page?object_id=' + document.id + '&access-token='+CmisService.token+'&t='+(new Date()).valueOf())
    .success (data)->
      page = 1
      if data.page_number
        page = data.page_number
      url = url+'#page=' + page
      $scope.previewUrl = $sce.trustAsResourceUrl(url)
    .error (error)->
      $scope.previewUrl = $sce.trustAsResourceUrl(url)

  $scope.preview = (document)->
    if !document.isDocument()
      return false
    if !Utils.canPreview(document)
      $translate('document_can_not_preview').then (text)->
        Utils.warning(text)
      return false

    CmisServiceSession.getObject(document.id).ok (data)->
      $scope.choseFile = document
      document.previewPdf = null
      if window.viewDocument && typeof window.viewDocument == 'function'
        objectId = document.id
        downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true)
        indexUrl = ''
        fileName = document.name
        fileSize = document.contentStreamLength
        document.getRenditions ()->
          if document.renditions
            for rendition,i in document.renditions
              if rendition.kind == 'smx:linearized_pdf'
                downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})
              else if rendition.kind == 'smx:linearized_index'
                indexUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})

              #  phantom online use origin file instead linearized_pdf
              if CmisService.device == 'phantom-online' || CmisService.device == 'reader-online'
                downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true)
                if rendition.kind == 'smx:converted_pdf' && rendition.length == 0
                  return Utils.warning($translate.instant('document_can_not_preview'))

              if rendition.kind == 'smx:converted_pdf' && rendition.length != 0
                downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})
          console.log(downloadUrl)
          window.viewDocument(objectId, downloadUrl, indexUrl, fileName, fileSize, '')
          console.log "call windown.viewDocument"
      else
        isAllowPreview = true
        document.getRenditions ()->
          if document.renditions
            console.log(document)
            for rendition,i in document.renditions
              if rendition.kind == 'smx:converted_pdf'
                if rendition.length == 0
                  isAllowPreview = false
            if isAllowPreview
              $scope.pdfPreview(document)
            else
              $translate('document_can_not_preview').then (text)->
                Utils.warning(text)
          else
            $scope.pdfPreview(document)
      Utils.sendGaEvent("Document", "Preview", document.id)
      document.createActivity "view-document", {document_name: document.name, document_id: document.id}
    .notOk (r)->
      if Utils.handleCmis401Error(r)
        return
      jsonData = JSON.parse(r.text)
      console.log(jsonData);
      if jsonData.errorCode == '671'
        jsonData.message = jsonData.exception+ ' ' + jsonData.message;
      #          $rootScope.translateErrorMsg(jsonData)
      Utils.warning(jsonData.message)

  #    else if window.jsViewDocument && typeof window.jsViewDocument == 'function'
  #      $scope.isFullScreenPreview = true
  #      $scope.choseFile.previewPdf = true
  #      window.jsViewDocument(document.id, document.drmKey, document.lastModificationDate)
  #    if previewActivity
  #      document.createActivity "view-document", {document_name: document.name, document_id: document.id}


##
#  dataType str 'cmis:lastModificationDate' 'cmis:creationDate' ...
#  dateInterval obj {after:'2016-12-13',before:'2016-12-16'}
#  property dateInterval.before can be null
##
  console.log ApiService
  getMineTypeValue = (obj,key)->
    if obj&&obj[key]
      return obj[key]
    else
      return '%'+key+'%'

  dateSql = (dataType,date)->
    # 传过来一个 日期格式 比如 2016-12-13
    # sql 只接受指定的 格式    2016-12-13T00:00:00
    #
    formatDate = ''
    dateKeymap = {
      lastModificationDateAfter:{
        cmisTag:'cmis:lastModificationDate'
        sign:'>='
      }
      lastAddedDateAfter:{
        cmisTag:'cmis:creationDate'
        sign:'>='
      }
  #      lastViewedDateAfter:{
  #        cmisTag:'cmis:lastModificationDate'
  #        sign:'>='
  #      }
    }
    if dataType == 'lastViewedDateAfter' || !dateKeymap[dataType]
      return ''

    formatDate = date+'T00:00:00'
#    timestamp
    sql = dateKeymap[dataType]['cmisTag'] + dateKeymap[dataType]['sign'] + " TIMESTAMP '"+ formatDate+"'"
    sql
  fileAddedBySql = (device)->
    map={
      fxt_mb_win:'Foxit MobilePDF for Windows'
      cloud_reading_web:'Cloud Reading Web'
      fxt_mb_ios:'Foxit MobilePDF for iOS'
      fxt_mb_and:'Foxit MobilePDF for Android'
      reader_mac:'Foxit Reader for Mac'
      reader_linux:'Foxit Reader for Linux'
    }
    if(!map[device])
      return ''
    #  select * from smxc:docWithSource WHERE smxc:addedBy='Foxit MobilePDF for Windows' AND IN_TREE('cc76b247-9834-4e4c-972a-668452bdb6c5')  必须类似这样的 sql 而非 cmis:document
    sql = "select * from smxc:docWithSource WHERE smxc:addedBy LIKE '"+map[device]+"' AND IN_TREE('"+$scope.tree[0]['id']+"')"
    sql

  fileMineTypeSql = (fileMineType)->
    # type of file
    mineTypeMap = {
      pdf:'application/pdf'
      zip:'application/zip | application/x-rar-compressed'
      image:'image%'
      text:'text%'
      ppt:'application/vnd.ms-powerpoint | application/vnd.openxmlformats-officedocument.presentationml.presentation'
      html:'text/html'
      video:'video%'
      excel:'application/vnd.ms-excel | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      word:'application/msword | application/vnd.openxmlformats-officedocument.wordprocessingml.document'
#      pptx:'application/vnd.openxmlformats-officedocument.presentationml.presentation'
#      xlsx:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
    multipleSql = getMineTypeValue(mineTypeMap,fileMineType).indexOf('|')
    sqlArr = []

    if multipleSql!= -1
#      Todo 写一个去除空格的函数 底下写成for 循环可能会有多个 值 传进来
      sqlArr[0]=getMineTypeValue(mineTypeMap,fileMineType).split('|')[0].slice(0,getMineTypeValue(mineTypeMap,fileMineType).split('|')[0].length-1)
      sqlArr[1]=getMineTypeValue(mineTypeMap,fileMineType).split('|')[1].slice(1)
#      console.log(sqlArr)
      sql = "(cmis:contentStreamMimeType LIKE '"+sqlArr[0]+"' OR cmis:contentStreamMimeType LIKE '"+sqlArr[1]+"')"
    else
      sql = "cmis:contentStreamMimeType LIKE '"+getMineTypeValue(mineTypeMap,fileMineType)+"'"
#    console.log sql
    sql
  fileTypeSql = (fileType)->
    # folder or file
    if fileType=='document'
      $scope.searchTypeSql = "SELECT * from cmis:document WHERE"
    else
      $scope.searchTypeSql = "SELECT * from cmis:folder WHERE"
  fileNameSql = (name)->
#    url 需要 decode
    sql = "cmis:name LIKE '%"+decodeURI(name)+"%'"
    sql
# above  把 字面量 翻译成 sql 语句

#  url para  a=b&c=d  => {a:b,c:d}
  urlParaToObj = (urlPara)->
    obj = {}
    if urlPara.indexOf('&')!=-1
      arr = urlPara.split('&')
      for i in arr
        obj[i.split('=')[0]]=i.split('=')[1]
    else
      obj[urlPara.split('=')[0]]=urlPara.split('=')[1]
    obj
  translateToSql = (key,value)->
    sql = ''
    if key.indexOf('Date')!=-1
      sql = dateSql(key,value)
    if key.indexOf('fileMineType')!=-1
      sql = fileMineTypeSql(value)
    if key.indexOf('title')!=-1
      sql = fileNameSql(value)
    if key.indexOf('fileAddedByDevice')!=-1
      sql = fileAddedBySql(value)
    if key.indexOf('type')!=-1
      fileTypeSql(value)
    sql

#    sql 前后缀
  adjustSql = (sqlSentence)->
    # 前缀 select * from cmis:document where
    # 后缀 IN_TREE()
    if($scope.searchTypeSql)
      prefix = $scope.searchTypeSql
    else
      prefix = 'SELECT * from cmis:document WHERE'
    suffix = "IN_TREE('"+$scope.tree[0]['id']+"')"
    sql = prefix+sqlSentence+suffix
    sql


  sqlSentences = (anchor)->
#    console.log anchor
    sentence = anchor.slice(anchor.lastIndexOf('/')+1)
    sentenceObj = urlParaToObj(sentence)
#    console.log('sentenceObj',sentenceObj)
    sql=' '

    for cmisTag,value of sentenceObj
      if translateToSql(cmisTag,value)
        sql=sql+translateToSql(cmisTag,value)+' AND '
    sql = adjustSql(sql)
#    console.log('sql',sql)
    return sql
  $scope.searchResult = []
  $scope.searchModeIsOn=false
  $scope.searchResult.name = ''
  if Utils.searchType then $scope.searchType = Utils.searchType else $scope.searchType= 'all'
  $scope.query={}
  $scope.query.str=''

  # chosenOptions remember last options
  $scope.chosenOptions=null
  $scope.advancedSearch = ()->
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "advanced-search.html",
      controller: 'advancedSearchModal'
      windowClass:'modal-opacity advaced-search-modal'
      resolve: {
        currentFolder: ()->
          $scope.currentFolder
        scope: ()->
          $scope
        searchModeIsOn: ()->
          $scope.searchModeIsOn
        chosenOptions: ()->
          $scope.chosenOptions
        location: ()->
          $location
      }
    }
    modalInstance.result.then (chosenOptions)->
      $scope.chosenOptions=chosenOptions

  $scope.search = (title,type,query)->
#    console.log Utils
    if CmisService.isAndroid || CmisService.isIOS
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    if title&&title.length>0
      if Utils.sqlContainIllegalChar(title)
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return
    anchorBeforeChange = $location.url()
    $scope.searchModeIsOn=true
    if title||type
      query = 'title='+title+'&type='+type
      if type
        $scope.searchType = type
        Utils.searchType = type
    else
      queryObj = urlParaToObj(query)
#      console.log('queryObj',queryObj)

      # set type 'document' 'folder' 'all_type'
      if queryObj && queryObj['type']
        $scope.searchType = queryObj['type']
        Utils.searchType = queryObj['type']
      else
        $scope.searchType = 'document'
        Utils.searchType = 'document'
      # set search keyword
      if queryObj && queryObj['title']
        $scope.query.str = queryObj['title']
      else
        $scope.query.str = ''

    #    search 主要是为了 改变url
    console.log('search 方法里面的 searchType')
    console.log($scope.searchType)
    $location.path(anchorPrefix+'/search/'+query, false)
    anchor = anchorPrefix+'/search/'+query
    #    console.log('encodeURIComponent',encodeURIComponent(anchor))
    #    console.log('encodeURI',encodeURI(anchor))
    if encodeURI(anchor) == anchorBeforeChange
      Utils.loadingSearchResult = false
      $scope.loadingSearchResult = Utils.loadingSearchResult
    else
      Utils.loadingSearchResult = true
      $scope.loadingSearchResult = Utils.loadingSearchResult
    $timeout(()->
      $scope.$apply()
    ,0)
  $scope.setSearchType = (query,type)->
    if !query
      query=''
    if !type
      $scope.searchType = 'all'
      Utils.searchType = 'all'
    else
      Utils.searchType = type
      $scope.searchType = type
    #    $scope.searchType = type
    #    $location.path('/search?query='+query+'&type='+type, false)
    querySentence = 'title='+query+'&type='+type
    $scope.search(null,null,querySentence)
  $scope.cancelSearch = ()->
    $scope.searchModeIsOn=false
    $scope.query.str = ''
    $scope.searchResult = []
    $scope.searchResult.name = ''
    $scope.searchResult.allowableActions={}
    $scope.searchResult.allowableActions.canCreateDocument=false
    anchor = localStorageService.get 'lastAnchor'
    if anchor
      $location.path(anchor, false)
    else
      rootFolderAnchor = 'folder/'+Utils.rootFolder.id
      $location.path(rootFolderAnchor, false)
#      $scope.openFolder(Utils.rootFolder)

  $scope.doActionFromAnchor = (anchor)->
    Utils.currentUrl = '#'+anchor
    if CmisService.isAndroid || CmisService.isIOS

      anchor = anchor.replace('/app/my','')
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    anchors = anchor.substr(1).split('/')

    if anchors[0] == 'folder'
      folderId = anchors[1]
      folder = ModelService.allFiles[folderId]
      if Utils.loadingSearchResult
        Utils.loadingSearchResult=false
        $scope.loadingSearchResult=Utils.loadingSearchResult
      if folder
        $scope.openFolder(folder)
      else
        $scope.openFolder(ModelService.tree[0])
    else if anchors[0] == 'file'
      fileId = anchors[1]
      document = ModelService.allFiles[fileId]
      if Utils.loadingSearchResult
        Utils.loadingSearchResult=false
        $scope.loadingSearchResult=Utils.loadingSearchResult
      if document
        parent = document.getParent()
        $scope.openFolder(parent)
        $scope.preview document
      else
        CmisServiceSession.getObject(fileId).ok (data)->
          document = ModelService.createDocument data
          parentPath = document.path.substr(0, document.path.lastIndexOf('/')).replace(/#/g, '%23')
          CmisServiceSession.getObjectByPath(parentPath).ok (data)->
            folderId = data.succinctProperties['cmis:objectId']
            folder = ModelService.allFiles[folderId]
            if folder
              $scope.openFolder(folder)
            $scope.choseFile = document
            #            $timeout ()->
            $scope.preview document
#            ,
#              1000
        .notOk (r)->
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          console.log(jsonData);
          #          $rootScope.translateErrorMsg(jsonData)
          Utils.warning(jsonData.message)
          #    for the search
    else if anchors[0] == 'search'
      console.log anchor
#      handle refresh
      index = anchor.lastIndexOf('/')
      urlPara = anchor.slice(index+1)
      urlObj = urlParaToObj(urlPara)
      Utils.searchType = urlObj && urlObj.type
      name = urlObj && decodeURI(urlObj.title)
      if !$scope.searchModeIsOn
        $scope.searchModeIsOn=true
      sql = sqlSentences(anchor)
      console.log('@@@@@@@')
      console.log(sql)
#      return false

      if Utils.searchType=='all'
        sqlForDoc = "SELECT * from cmis:document WHERE IN_TREE('" + $scope.tree[0]['id'] + "') AND cmis:name LIKE '%" + name + "%'"
        sqlForFolder = "SELECT * from cmis:folder WHERE IN_TREE('" + $scope.tree[0]['id'] + "') AND cmis:name LIKE '%" + name + "%'"


        CmisServiceSession.query(sqlForFolder).ok((data)->
#        console.log(data)
#        console.log ModelService
          $scope.searchResult.name= 'search_result'
          $scope.searchResult.children = []
          $scope.folderTree=$scope.searchResult
          for file in data.results
            if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
#              console.log('does not contain')
              if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                ModelService.createFolder(file)
              else
                ModelService.createDocument(file)
            $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])
          CmisServiceSession.query(sqlForDoc).ok((data)->
            for file in data.results
              if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
#                console.log('does not contain')
                if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                  ModelService.createFolder(file)
                else
                  ModelService.createDocument(file)
              $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])
            Utils.loadingSearchResult=false
            $scope.loadingSearchResult=Utils.loadingSearchResult
            $scope.currentFolder = $scope.searchResult
            $scope.currentFolder=$scope.searchResult
            if $scope.searchResult.length == 0
              $scope.choseFile = $scope.tree[0]
            Utils.sendGaEvent('Document','Search',sql)
            $timeout(()->
              $scope.$apply()
            ,0)
          ).notOk((err)->
            if Utils.handleCmis401Error(err)
              return
            Utils.loadingSearchResult=false
            $scope.loadingSearchResult=Utils.loadingSearchResult
            Utils.warning(err)
          )
        ).notOk((err)->
          if Utils.handleCmis401Error(err)
            return
          Utils.loadingSearchResult=false
          $scope.loadingSearchResult=Utils.loadingSearchResult
          Utils.warning(err)
        )
      else
        sql = sqlSentences(anchor)
#        args1 = {
#          succinct:true
#          cmisaction:'query'
#          statement:sql
#          searchAllVersions:false
#        }

        callback = ()->
          $scope.currentFolder=$scope.searchResult
          $scope.loadingSearchResult=false
          Utils.loadingSearchResult=false
          if $scope.searchResult.length == 0
            $scope.choseFile = $scope.tree[0]
          $timeout(()->
            $scope.$apply()
          ,0)
#        Intersection = (arr1,arr2,arr3)->
##          return the common key
#          object = {}
#
#          object.arr1 = {
#            origin:arr1
#            len:arr1.length
#          }
#          object.arr2 = {
#            origin:arr2
#            len:arr2.length
#          }
#          object.arr3 = {
#            origin:arr3
#            len:arr3.length
#          }
#          if object.arr1.len>0 && object.arr2.len>0 && object.arr3.len>0
#            console.log('都不为0')
#
#          else
#            return []
#
#
#
#
#        needUsePhpApi = false
#        needSmxcSql = false
#        if anchor.indexOf('lastViewedDateAfter')>-1
#          needUsePhpApi = true
#
#        if anchor.indexOf('lastViewedDateAfter')>-1
#          sentence = anchor.slice(anchor.lastIndexOf('/')+1)
#          sentenceObj = urlParaToObj(sentence)
#          lastViewedDateAfterValue = sentenceObj['lastViewedDateAfter']
#          sqlOfSmxc = fileAddedBySql(lastViewedDateAfterValue)
#          if sqlOfSmxc
#            needSmxcSql = true
#            argsForSmxc = {
#              succinct:true
#              cmisaction:'query'
#              statement:sqlOfSmxc
#              searchAllVersions:false
#            }
#
#        $.when(ApiService.cmisSQL(args1),ApiService.cmisSQL(args))
#        .done((data1,data2,data3)->
#
#        ).fail(()->
#          console.log('yyy')
#        )
#
#        return false
        CmisServiceSession.query(sql).ok((data)->
          $scope.searchResult.name= 'search_result'
          $scope.searchResult.children = []
          $scope.folderTree=$scope.searchResult
          for file in data.results
            if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
              console.log('does not contain')
              if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                ModelService.createFolder(file)
              else
                ModelService.createDocument(file)
            $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])

          # lastViewedDateAfter 发起一次 php api 请求
          if(anchor.indexOf('lastViewedDateAfter')>-1)
            # 重新构成数组
            console.log()
            sentence = anchor.slice(anchor.lastIndexOf('/')+1)
            sentenceObj = urlParaToObj(sentence)
            date = sentenceObj.lastViewedDateAfter  # 2017-02-22

            currentDate = Utils.formatDate(new Date())
            console.log(currentDate)
            days = Utils.calculateDaysBetween(date,currentDate)+1
            if parseInt(days)<0
              $scope.searchResult.children = []
              callback()
              return false
            else
              $scope.searchResult.children = []
              ApiService.getRecentViewedFile(days,(data)->
                if data&&data.length
                  for id in data
                    if(ModelService.allFiles[id])
                      $scope.searchResult.children.push(ModelService.allFiles[id])
                  callback()
                else
                  callback()
              )
          else
            callback()
          Utils.sendGaEvent('Document','Search',sql)
        ).notOk((err)->
          if Utils.handleCmis401Error(err)
            return
          $scope.loadingSearchResult=false
          Utils.loadingSearchResult=false
          Utils.warning(err)
        )
    else
#      url 未匹配的 跳到根目录
      $location.url(anchorPrefix)
      return
  $scope.openFolder = (folder)->
    if $scope.searchModeIsOn
      $scope.cancelSearch()
    window.CloudReading.choseFile=null
    $scope.isFullScreenPreview = false
    $scope.multipleChooseFiles=[]
    $scope.multipleChooseFilesId=[]
    folder.getAces()
    if $scope.choseFile != folder && $(document.body).width() > 1000
      $scope.choseFile = folder
      Utils.choseFile = folder
    folder.isExpand = true
    $scope.currentFolder = folder
    Utils.currentFolder = folder
    for parent in folder.getParents()
      parent.isExpand = true
    if folder.loading
      return false
    $timeout(()->
      $scope.$apply()
    )
    folder.getRenditions()
    folder.loading = true
    folder.getChildren $scope, (obj)->
      $scope.$broadcast('get-children-ready')
      folder.loading = false
      $timeout(()->
        $scope.$apply()
      ,0)
    ,(errcallback)->
      folder.loading = false
      $timeout(()->
        $scope.$apply()
      )

#  $scope.$on('get-children-ready',()->
#    folder.loading = false
#  )
  $scope.openFolderFormAnchor = (rootFolder)->
    anchor = $location.url()
#    console.log('openFolderFormAnchor',anchor)
    # check email is current user if not reset the localstorage
    userEmail = CmisService.email
    storedUserEmail = localStorageService.get 'userEmail'
    if !storedUserEmail || storedUserEmail != userEmail
      console.log('here')
      localStorageService.set "userEmail" , userEmail
      localStorageService.set "lastAnchor" , ''
      localStorageService.set "lastAnchorPath" , ''
    if anchor
      $scope.doActionFromAnchor(anchor)
      id = anchor.slice(anchor.lastIndexOf('/')+1)
      #          console.log(id)
      folder = ModelService.allFiles[id]
      #          console.log folder
      if folder
        localStorageService.set "lastAnchorPath" , folder.path
      else
        return
    else
      lastAnchor = localStorageService.get "lastAnchor"
      if lastAnchor
        $scope.doActionFromAnchor(lastAnchor)
        id=lastAnchor.slice(lastAnchor.lastIndexOf('/')+1)
        console.log id
        folder = ModelService.allFiles[id]
        if folder
          localStorageService.set "lastAnchorPath" , folder.path
        else
          return
      else
        localStorageService.set "lastAnchorPath" , CmisService.path
        $scope.openFolder(rootFolder)

  $scope.refreshCurFolderList=()->
    console.log('====refresh====')
    if $scope.searchResult.name
#      Todo 暂时的处理方案 url 有点丑陋 后面在调整
      location.hash = location.hash+'&time='+Date.parse(new Date())/1000
      $scope.currentFolder.children = null
      $scope.currentFolder.loading=true
#      $scope.search null,null
      $scope.$broadcast 'scroll.refreshComplete'
      return
    $scope.currentFolder.children = null
    $scope.currentFolder.loading=true
#    $timeout ->
##      $scope.currentFolder.folderList = []
#      $scope.currentFolder.children = null
#      $scope.currentFolder.loading=true
#      $scope.$apply()
#      return

    $scope.currentFolder.getChildren $scope, ((obj) ->
      $timeout (->
        $scope.$digest()
        return
      ), 0
      $scope.$broadcast 'scroll.refreshComplete'
      $scope.currentFolder.loading = false
      Utils.sendGaEvent('Folder','Refresh',$scope.currentFolder.id)
      return
    ), ((error) ->
      Utils.translateErrorMsg error.body
      $scope.$broadcast 'scroll.refreshComplete'
    ), true

  if CmisServiceSession && CmisServiceSession.defaultRepository
    $scope.progress = 100
    $scope.tree = ModelService.tree
    $scope.depth = 1
#    console.log $scope.tree
    $scope.openFolderFormAnchor()
  else
    checkSuccess = $timeout ()->
      $scope.serverError = true
    ,
      15000
    CmisServiceSession.loadRepositories().ok (res)->
      if $scope.serverError
        return false
      $timeout.cancel(checkSuccess)
      CmisServiceSession.defaultRepository = res[CmisService.repository]
      localStorageService.set "rootFolderUrl" , res[CmisService.repository]['rootFolderUrl']
      $scope.progress = 50
      CmisServiceSession.getObjectByPath(CmisService.path, {includeAllowableActions:true}).ok (data)->
#      console.log('getObjectByPath',data)
        $scope.progress = 100

        cancel_file_checkout = localStorageService.get 'cancel-file-checkout'
        if cancel_file_checkout
          Utils.isUploadNewVersioning = false
          CmisService.session.cancelCheckOut(cancel_file_checkout).ok ()->
            localStorageService.set 'cancel-file-checkout', ''
          .notOk (r)->
            if Utils.handleCmis401Error(r)
              return
            localStorageService.set 'cancel-file-checkout', ''

        rootFolder = ModelService.createFolder data
        Utils.rootFolder = rootFolder
        ModelService.setRoot(rootFolder)
        $scope.tree = ModelService.tree
        $scope.depth = 1
        CmisServiceSession.getFolderTree(rootFolder.id, null, {includeAllowableActions:true}).ok (data)->
#        console.log('getFolderTree',data)
          rootFolder.folderList = ModelService.getChildrenFromData data
          $scope.openFolderFormAnchor(rootFolder)
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        #        $rootScope.translateErrorMsg(jsonData)
        Utils.warning(jsonData.message)

  $scope.sendViaEmail = (file)->
    Utils.sendGaEvent("Document", "SendEmail", file.id)
    if window.sendEmail
      if file.contentStreamLength < 20*1024*1024
        url = CmisServiceSession.getContentStreamURL(file.id,true)
        window.sendEmail(url,file.name)
      else
        $translate('document_too_big').then (text)->
          Utils.warning(text)

  $scope.getChildren = (folder)->
    #Loading return
    if $scope.loading
      return false
    $scope.multipleChooseFiles = []
    if $scope.choseFile != folder && $(document.body).width() > 1000
      $scope.choseFile = folder
      $scope.choseFile.getAces()
#      $timeout ()-> $scope.$apply()

    folder.getRenditions()
    if $scope.currentFolder == folder
      folder.isExpand = !folder.isExpand
    else
      folder.isExpand = true
      $scope.currentFolder = folder

    $scope.loading = true
    folder.getChildren $scope, (obj)->
      $scope.$broadcast('get-children-ready')
#      $scope.children = folder.children
      $scope.loading = false

  $scope.chooseFileById = (id)->
    if $scope.choseFile.id == id || id == null
      return
    CmisServiceSession.getFolderParent(id).ok (data)->
      folder = ModelService.createFolder data
      $scope.chooseFileByPath(folder.path, id)
    .notOk (r)->
      if Utils.handleCmis401Error(r)
        return
      jsonData = JSON.parse(r.text)
      Utils.warning(jsonData.exception+': '+jsonData.message)

  $scope.chooseFileByPath = (path, id, folder = null)->
    if !folder?
      folder = ModelService.tree[0]
    nextPath = path.substr(folder.path.length).split('/')[1]
    folder.getChildren $scope, (obj)->
      if nextPath
        currentFolder = f for f in folder.children when f.name == nextPath
        currentFolder.isExpand = true
        $scope.chooseFileByPath(path, id, currentFolder)
      else
        $scope.currentFolder = folder
        currentFile = f for f in folder.children when f.id == id
        $scope.dbClick(folder)
        $scope.chooseFile(currentFile)
        folder.isExpand = true
  $scope.scopeApply = (time = 200)->
    Utils.rebound(
      'root-scope-apply',
      ()->
        $scope.$apply()
    ,
      time
    )
  $scope.isDbclick=false
  $scope.timerForClick = false
  $scope.click = (file,event)->
    if event && event.button==2
      return
    if event
      event.stopPropagation()
    if ($scope.isDbclick)
      $scope.dbClick(file)
      if($scope.timerForClick)
        $scope.isDbclick = false
        clearTimeout($scope.timerForClick)
    else
      $scope.isDbclick = true
      $scope.timerForClick= setTimeout(()->
        $scope.chooseFile(file,event)
        $scope.isDbclick = false
      , 200)
  # show filedetail
  if !$scope.pluginUi
    $scope.detailPanelIsShow = true
  else
    $scope.detailPanelIsShow = false
  $scope.smallScreen=false
  adjustDetailPanel = ()->
    newValue = $(document).width()
    if newValue<700
      $scope.smallScreen=true
    else
      $scope.smallScreen=false
    if newValue<=1000
      $scope.closeFile()
    else
      $scope.showDetail()

  # 尝试过使用 watch 但是 apply 滞后 相应太慢
  window.onresize = ()->
    if !$scope.pluginUi
      adjustDetailPanel()
  $scope.showDetail = ()->
    if !$scope.choseFile
      $scope.choseFile = $scope.currentFolder
    $scope.detailPanelIsShow = true
  $scope.closeFile = ()->
    $scope.detailPanelIsShow = false
  if !$scope.pluginUi
    adjustDetailPanel()
  # end filedetail

  $scope.disableMerge = false
  $scope.handleMergeOption = ()->
    if($scope.multipleChooseFiles.length>10)
      $scope.disableMerge=true
    else
      $scope.disableMerge=false
  #  如果没有 按 ctrl 或者 metakey  那么选择的话 就是单选
  $scope.fileMouseUp = (file,event)->
    if $scope.startTime&&event.which==1&&!event.metaKey&&!event.ctrlKey
      $scope.multipleChooseFiles=[]
      $scope.multipleChooseFilesId=[]
      $scope.multipleChooseFiles=[file]
      $scope.multipleChooseFilesId=[file.id]
    $scope.startTime=false
  $scope.chooseFile = (file,event,up)->
    console.log file
#    console.log ModelService.allFiles
    if event
      event.stopPropagation()
    documentExistIndex =-1
    documentIdExistIndex =-1
    $scope.startTime=true
    if $scope.multipleChooseFiles && $scope.multipleChooseFiles.length
      documentExistIndex=$scope.multipleChooseFiles.indexOf(file)
    if $scope.multipleChooseFilesId && $scope.multipleChooseFilesId.length > 0
      documentIdExistIndex=$scope.multipleChooseFilesId.indexOf(file.id)
    $scope.choseFile = file if $scope.choseFile != file
    window.CloudReading.choseFile = $scope.choseFile
    file.getAces()
    if !file.renditions
      file.getRenditions(()->
        $timeout(()->
          $scope.$apply()
        )
      ,null,true)
    if file.isDocument()
      file.getVersions(null,(error)->
        $scope.translateErrorMsg(error.body)
      )
    #   handle cmd or ctrl click
    if event && event.metaKey || event && event.ctrlKey
      if $scope.fileSelectMode && $scope.fileSelectMode == 'single'
        return
      else
        if documentExistIndex==-1
          $scope.multipleChooseFiles.push(file)
          $scope.multipleChooseFilesId.push(file.id)
          $timeout(()->
            $scope.$apply()
          ,0)
          $scope.handleMergeOption()
  #        如果再一次点击取消选择
        else
          $scope.multipleChooseFiles.splice(documentExistIndex,1)
          $scope.multipleChooseFilesId.splice(documentExistIndex,1)
          $scope.choseFile = $scope.multipleChooseFiles[0] if $scope.multipleChooseFiles.length ==1
          $scope.choseFile = $scope.currentFolder if $scope.multipleChooseFiles.length ==0
          $scope.handleMergeOption()
          $timeout(()->
            $scope.$apply()
          ,0)

        window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
#    handle single choose file
    else
      if documentExistIndex==-1
        $scope.multipleChooseFiles=[]
        $scope.multipleChooseFilesId=[]
        $scope.multipleChooseFiles=[file]
        $scope.multipleChooseFilesId=[file.id]
        $scope.handleMergeOption()
        $timeout(()->
          $scope.$apply()
        ,0)
      else
        $timeout(()->
          $scope.$apply()
        ,0)
  $scope.expandFolder= (folder, event)->
    folder.isExpand = !folder.isExpand
    event.stopPropagation()

  $scope.dbClick = (document,e)->
    if $scope.filePickerModal=='saveAs' && document.isDocument() && !$scope.fromFillAndSign
      return false
    if $scope.filePickerModal=='saveAs' && document.isDocument() && $scope.fromFillAndSign
      console.log($scope.filePickerModal)
      if !document.isDocument()
        $scope.fillAndSign(document)
      return false
    if CmisService.isAndroid || CmisService.isIOS
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    if(e)
      e.stopPropagation()
    if document.isDocument()
#      $scope.preview(document)
      urlHashWillBe = '#/file/' + document.id
#      console.log('Utils.currentUrl',Utils.currentUrl)
#      console.log('urlHashWillBe ',urlHashWillBe)
      if Utils.currentUrl  && Utils.currentUrl != urlHashWillBe
        $location.path(anchorPrefix+'/file/' + document.id, false)
        parentFolder = document.getParent()
      else
        $scope.preview(document)
#      localStorageService.set "lastAnchorPath" , parentFolder.path
    else
#      $scope.getChildren(document)
      if !document.isExpand
        document.isExpand=true
      localStorageService.set "lastAnchorPath" , document.path
      $location.path(anchorPrefix+'/folder/' + document.id, false)
      localStorageService.set "lastAnchor" , anchorPrefix+'/folder/' + document.id

  $scope.closePreview = (event)->
    if event
      event.stopPropagation()
    if CmisService.isIOS
      $cordovaStatusbar = $injector.get('$cordovaStatusbar')
      $cordovaStatusbar.show()
    page = 1
    if location.href.indexOf('localhost')==-1
      if window.top.previewFrame && previewFrame.window && previewFrame.window.getCurrentPage
        page = previewFrame.window.getCurrentPage()
    $http.post(CmisService.baseUrl + 'api/document/post-doc-preview-page?&access-token='+CmisService.token,{object_id:$scope.choseFile.id,page_number:page.currentPage})
    .success (data)->
      console.log(data)
    .error (error)->
      console.log(error)
    $scope.iframePdf = false
    $scope.isNormalFilePreview=false
    $scope.isFullScreenPreview = false
    $scope.previewUrl = ''
    if !CmisService.isAndroid && !CmisService.isIOS
      $location.path('/folder/' + $scope.currentFolder.id, false)



  $scope.deleteFolder = (folderForDel, event)->
    if(ContextMenuService.menuElement)
      ContextMenuService.close(ContextMenuService.menuElement)
    event.stopPropagation()
    $translate('folder_delete_confirm').then (text)->
      Utils.confirm text,'','','', ()->
        parent = folderForDel.getParent()
        CmisServiceSession.deleteTree(folderForDel.id, true)
        .ok ()->
          if $scope.searchModeIsOn
            temperParent = $scope.currentFolder
            theIndex = j for tmp,j in temperParent.children when tmp.id == folderForDel.id
            if theIndex!=-1
              temperParent.children.splice(theIndex,1)
          folderListIndex = i for folder,i in parent.folderList when folderForDel.id == folder.id
          parent.folderList.splice(folderListIndex,1)
          index = i for folder,i in parent.children when folderForDel.id == folder.id
          if index!=-1
            parent.children.splice(index,1)
          $translate('delete_folder_success').then (text)->
            Utils.success text
          $scope.choseFile = $scope.currentFolder
          Utils.sendGaEvent("Folder", "Delete", folderForDel.id)
          parent.createActivity "delete-folder", {name: folderForDel.name,from_folder_name:parent.name, del_id:folderForDel.id}
        .notOk (r)->
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          $scope.translateErrorMsg(jsonData)

  $scope.delete = (document)->
#    console.log document
    $translate('file_delete_confirm').then (text)->
      Utils.confirm text,'','','', ()->
        CmisServiceSession.deleteObject(document.id, true)
        .ok ()->
          # need to handle search result delete update view
          parent = $scope.currentFolder
          if $scope.searchModeIsOn
            index = j for tmp,j in parent.children when tmp.id == document.id
            if index!=-1
              parent.children.splice(index,1)
          # absolute parent
          absolutePare = document.getParent()
          if absolutePare && absolutePare.children
            theIndex = i for tmp,i in absolutePare.children when tmp.id == document.id
            if theIndex!=-1
              absolutePare.children.splice(theIndex,1)
          $scope.choseFile = $scope.currentFolder
          $translate('delete_file_success').then (text)->
            Utils.success text
          # delete fns file post   api/fns/delete-doc-from-cloud-reading?doc_id=dc40ee79-49ae-462d-9539-0dbebec72330%2C1.0&access-token=58f6c44fe4b0ada4aeb3c0a6%2Cww002%40mailinator.com
          postData = {
            doc_id:document.id
          }
          $.ajax({
            type: 'GET'
            url:CmisService.baseUrl+'api/fns/delete-doc-from-cloud-reading?doc_id='+document.id+'&access-token='+CmisService.token,
            beforeSend: (request)->
              request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
            success: (data)->
              console.log('====fns-delete====')
              console.log(data)
            error: (err)->
              console.log(err)
          })
          Utils.sendGaEvent("Document", "Delete", document.id)
          absolutePare.createActivity "delete-document", {name: document.name,from_folder_name:absolutePare.name, del_id:document.id}
        .notOk (r)->
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          $scope.translateErrorMsg(jsonData)
  $scope.multipleDel=(event)->
#    ContextMenuService 就是 右键context的 服务 改写了原来的  js 库  把close 方法 放到了ContextMenuService上了 供我们使用
    if(ContextMenuService.menuElement)
      ContextMenuService.close(ContextMenuService.menuElement)
    #    不让他冒泡 选中的文件 就不会 变了
    event.stopPropagation()
    #    删去的总数是 知道的
    #    $('body').click()
    needSuccessCallBack=false
    $scope.tempMultiFiles=$scope.multipleChooseFiles
    $scope.multipleChooseFiles=$scope.tempMultiFiles
    $uibModal.open {
      animation: true,
      templateUrl: templatePath + "delete-confirm.html",
      controller: 'deleteModal'
      resolve: {
        files: ()->
          if $scope.multipleChooseFiles.length > 1
            $scope.multipleChooseFiles
          else
            [$scope.choseFile]
        currentFolder: ()->
          $scope.currentFolder
        needSuccessCallBack: ()->
          needSuccessCallBack
        scope: ()->
          $scope
        searchModeIsOn: ()->
          $scope.searchModeIsOn
      }
    }
  $scope.download = (document)->
    if !CmisService.allowDownload
      Utils.warning('Document download not permitted')
      return
    if window.downloadDocument && typeof window.downloadDocument == 'function'
      if CmisService.isAndroid || CmisService.isIOS
        downloadDocument(document)
      else
        downloadDocument(document.id)
      return false
    Utils.sendGaEvent("Document", "Download", document.id)
    document.createActivity "download-document", {document_name: document.name, document_id: document.id}
    $translate('downloading').then (text)->
      Loading.open text
    url = CmisServiceSession.getContentStreamURL(document.id, true)
    x=new XMLHttpRequest()
    x.open("GET", url, true)
    x.responseType = 'blob'
    x.setRequestHeader("Authorization", "Bearer " + CmisService.token)
    x.onload= ()->
      saveAs(x.response, document.name)
      Loading.close()
    x.send()

  $scope.downloadVersion = (version)->
    if !CmisService.allowDownload
      Utils.warning('Document download not permitted')
      return
    if window.downloadDocument && typeof window.downloadDocument == 'function'
      if CmisService.isAndroid || CmisService.isIOS
        document = {}
        document.id = version.succinctProperties['cmis:objectId']
        document.name = version.succinctProperties['cmis:name']
        document.contentStreamLength = version.succinctProperties['cmis:contentStreamLength']
        downloadDocument(document)
      else
        downloadDocument(version.succinctProperties['cmis:objectId'])
      return false
    Utils.sendGaEvent("Document", "DownloadVersion", version.succinctProperties['cmis:objectId'])
    $translate('downloading').then (text)->
      Loading.open text
    url = CmisServiceSession.getContentStreamURL(
      version.succinctProperties['cmis:objectId'],
      true
    )
    x=new XMLHttpRequest()
    x.open("GET", url, true)
    x.responseType = 'blob'
    x.setRequestHeader("Authorization", "Bearer " + CmisService.token)
    x.onload= ()->
      saveAs(x.response, version.succinctProperties['cmis:name'])
      Loading.close()
    x.send()

  $scope.upload = (files)->
    fileTooLarge = false
    maxFileSize = 30*1024*1024;
    if files.length
      if files.length==1
        if files[0].size > maxFileSize
          fileTooLarge = true
      else
        for file in files
          if file.size > maxFileSize
            fileTooLarge = true
            break
    if fileTooLarge
      if CmisService.device == 'phantom-online' # do not include 'reader-online'
        Utils.warning($translate.instant('phantom_limit_file_size'))
      else
        Utils.warning($translate.instant('file_too_big'))
      return
    isIOS = CmisService.isIOS
    $('#upload-file').after $('#upload-file').clone().val('')
    $('#upload-file').remove()
    if !$scope.tempFolder.allowableActions || !$scope.tempFolder.allowableActions.canCreateDocument
      $uibModal.open {
        animation: true,
        templateUrl: templatePath + "user-not-allowed-upload.html",
        controller: 'userNotAllowedUpload',
        windowTopClass: 'not-allowed-window',
        resolve: {}
      }
    else
      if files == null
        return false
      results = []
      i = 0
      j = 0
      len = files.length
      while j < len
        file = files[j]
        #fix ios all upload file has same name
        if isIOS and file.name.indexOf('image.') > -1
          i++
          date = file.lastModifiedDate
          year = date.getFullYear()
          month = if date.getMonth() + 1 > 9 then date.getMonth() + 1 else '0' + date.getMonth() + 1
          day = if date.getDate() > 9 then date.getDate() else '0' + date.getDate()
          hour = if date.getHours() > 9 then date.getHours() else '0' + date.getHours()
          minute = if date.getMinutes() > 9 then date.getMinutes() else '0' + date.getMinutes()
          second = if date.getSeconds() + i > 9 then date.getSeconds() + i else '0' + date.getSeconds() + i
          extName = Utils.getFileExt(file.name)
          fileNameForIos = '' + year + '-' + month + '-' + day + '-' + hour + minute + second + '.' + extName
          file.iosName = fileNameForIos
        #console.log('ios name rename')
        #console.log(fileNameForIos)
        #console.log(file)
        if !Utils.isAllowExtension(file)
          $translate('file_type_error', allowExtensions: CmisService.allowExtension.join(', ')).then (text) ->
            Utils.warning text
            return
          j++
          continue
        results.push UploadQueue.add(file, $scope.tempFolder.id, {
          'cmis:name': if isIOS and file.name.indexOf('image.') > -1 then file.iosName else file.name
          'cmis:objectTypeId': 'cmis:document'
        }, null, ()->
          $timeout(
            ()->
              $scope.$apply()
          ,0
          )
        )
        j++
#    $('#upload-file').after($('#upload-file').clone().val(""))
#    $('#upload-file').remove()
#    if !$scope.tempFolder.allowableActions.canCreateDocument
#      $uibModal.open {
#        animation: true,
#        templateUrl: templatePath + "user-not-allowed-upload.html",
#        controller: 'userNotAllowedUpload'
#        windowTopClass:'not-allowed-window',
#        resolve: {
#        }
#      }
#    else
#      if !files?
#        return false
#      for file in files
#        if !Utils.isAllowExtension(file)
#          $translate('file_type_error', {allowExtensions:CmisService.allowExtension.join(', ')}).then (text)->
#            Utils.warning(text)
#          continue
#        UploadQueue.add(file, $scope.tempFolder.id, {
#          'cmis:name': file.name,
#          'cmis:objectTypeId': 'cmis:document'
#        })

  $scope.safeApply = (expr)->
    try
      return $scope.$eval(expr)
    catch e
      console.log e
    finally
      $scope.$root.$digest
  $scope.openModifyFilePicker = (file)->
    $scope.tempFile = file
    isAndroid = CmisService.isAndroid
    if isAndroid
      $scope.createDocumentInAndroid(true)
    else
      $timeout ()->
        $('#modify-file').click()
      ,0
  $scope.openUploadFilePicker = (folder, dropFile = null)->
    if CmisService.isDrmRoom
      $uibModal.open {
        animation: true,
        templateUrl: templatePath + "upload-drn-file.html",
        controller: 'UploadDrnCtrl'
        resolve: {
          dropFile: ()->
            dropFile
          folder: ()->
            folder
          parentScope: ()->
            $scope
        }
      }
    else
      $scope.tempFolder = folder
      isAndroid = CmisService.isAndroid
      if isAndroid
        $scope.createDocumentInAndroid(false)
      else
        $timeout(()->
          $('#upload-file').click()
        ,0)

  $scope.createDocumentInAndroid = (isModify)->
    success =  (data)->
      file = {
        filepath:data.filepath,
        name:data.name,
        size:data.size,
        type:data.type,
      }
      files = new Array(file)
      if isModify
        $scope.modifyFile(file)
      else
        $scope.upload(files)

    errorFunction = (msg)->
      $translate('UPLOAD_FILE_ERROR_ANDROID').then (text)->
        Utils.warning(text)
    filechooser.open({},success, errorFunction)

  $scope.setContentStream=(file)->
    # file  input select file
    # cmisFile ModelService file object
    okFunction = (checkInObj)->
      Utils.isUploadNewVersioning = false
      Utils.sendGaEvent("Document", "UploadNewVersion", $scope.tempFile.id)
      $scope.tempFile.createActivity "upload-version", {document_name: $scope.tempFile.name, document_id: $scope.tempFile.id}
      $scope.tempFile.getVersions ()->
        Loading.close()
        $('#modify-file').val('')
        $scope.choseFile = $scope.tempFile
        #          refresh 并不会更新 id 导致后续的bug refresh 已经改了 会更新id
        $scope.tempFile.refresh(()->
          $scope.choseFile.getRenditions(null,null,true)
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $scope.multipleChooseFiles=[$scope.choseFile]
          $scope.multipleChooseFilesId=[$scope.choseFile.id]
        )
        $translate('upload_succ').then (text)->
          Utils.success text
        $timeout ()-> $scope.$apply()
      , null , true

    notOkFunction = (r)->
      if Utils.handleCmis401Error(r)
        return
      Utils.isUploadNewVersioning = false
      jsonData = JSON.parse(r.text)
      Loading.close()
      $('#modify-file').val('')
      Utils.warning(jsonData.message)
    if CmisService.isAndroid
      filePath = encodeURI(file.filepath)
      # for android
      console.log 'file://' + filePath
      window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
        console.log fileEntry
        fileEntry.file (localfile) ->
          reader = undefined
          reader = new FileReader

          reader.onloadend = (fileReadResult) ->
            data = undefined
            data = new Uint8Array(fileReadResult.target.result)
            fileBlobData = new Blob([ data ], type: file.type)
            CmisServiceSession.setContentStream($scope.tempFile.id,fileBlobData,true,{},null)
            .ok(okFunction).notOk(notOkFunction)
          reader.readAsArrayBuffer localfile
      ), (error) ->
        console.log error
    else
      reader = undefined
      reader = new FileReader
      reader.onloadend = (fileReadResult) ->
        data = undefined
        data = new Uint8Array(fileReadResult.target.result)
        fileBlobData = new Blob([ data ], type: file.type)
        CmisServiceSession.setContentStream($scope.tempFile.id,fileBlobData,true,{},null)
        .ok(okFunction).notOk(notOkFunction)
      reader.readAsArrayBuffer file

  $scope.checkIn = (file)->

    okFunction = (checkInObj)->
      Utils.isUploadNewVersioning = false
      Utils.sendGaEvent("Document", "UploadNewVersion", $scope.tempFile.id)
      $scope.tempFile.createActivity "upload-version", {document_name: $scope.tempFile.name, document_id: $scope.tempFile.id}
      $scope.tempFile.getVersions ()->
        Utils.isUploadNewVersioning = false
        Loading.close()
        $('#modify-file').val('')
        $scope.choseFile = $scope.tempFile
        #          refresh 并不会更新 id 导致后续的bug refresh 已经改了 会更新id
        $scope.tempFile.refresh(()->
          $scope.choseFile.getRenditions(null,null,true)
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $scope.multipleChooseFiles=[$scope.choseFile]
          $scope.multipleChooseFilesId=[$scope.choseFile.id]
        )

        $translate('upload_succ').then (text)->
          Utils.success text
        $timeout ()-> $scope.$apply()
      , null , true

    notOkFunction = (r)->
      if Utils.handleCmis401Error(r)
        return
      Utils.isUploadNewVersioning = false
      jsonData = JSON.parse(r.text)
      Loading.close()
      $('#modify-file').val('')
      Utils.warning(jsonData.message)

    if CmisService.isAndroid
      filePath = encodeURI(file.filepath)
      # for android
      console.log 'file://' + filePath
      window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
        console.log fileEntry
        fileEntry.file (localfile) ->
          reader = undefined
          reader = new FileReader

          reader.onloadend = (fileReadResult) ->
            data = undefined
            data = new Uint8Array(fileReadResult.target.result)
            fileBolbData = new Blob([ data ], type: file.type)

            CmisServiceSession.checkIn($scope.tempFile.id, true, null, fileBolbData)
            .ok(okFunction).notOk(notOkFunction)

          reader.readAsArrayBuffer localfile
      ), (error) ->
        console.log error
    else
      CmisServiceSession.checkIn(
        $scope.tempFile.id,
        true,
        null,
        file
      ).ok(okFunction).notOk(notOkFunction)

  $scope.modifyFile = (file)->
    # file 是input 里面的file 对象
    $('#modify-file').after($('#modify-file').clone().val(""))
    $('#modify-file').remove()
    if !file?
      return false
    Utils.isUploadNewVersioning = true;
    console.log(Utils.isUploadNewVersioning);
    $scope.modifyNewFile = file
#    $scope.checkIn(file)
#        if new version of the file has different name then pop up a confirm window
    if $scope.choseFile.name!=file.name
      $translate('update_with_new_name').then (text)->
        $uibModal.open {
          animation: true,
          templateUrl: templatePath + "confirm.html",
          controller: 'uploadNewVersionCtrl'
          windowClass:'modal-opacity'
          resolve: {
            parentScope: ()->
              $scope
            rootScope:()->
              $scope
            content:()->
              text
          }
        }
#     same name then upload
    else
      $translate('uploading').then (text)->
        if $scope.progressHandler
          $scope.progressHandler.dismiss()
          UploadQueue.modal=false
        Loading.open text
      $scope.setContentStream($scope.modifyNewFile)



#      if $scope.tempFile.isVersionSeriesCheckedOut
#        $scope.checkIn(file)
#      else
#        CmisServiceSession.checkOut($scope.tempFile.id).ok (checkOutObj)->
#          $scope.checkIn(file)
#        .notOk (r)->
#          if Utils.handleCmis401Error(r)
#            return
#          Loading.close()
#          jsonData = JSON.parse(r.text)
#          Utils.warning(jsonData.message)



  $scope.rename = (file)->
#   当执行该方法  必须立马把choose file 切换到当前的文件上
    $scope.choseFile = file
    $uibModal.open {
      animation: true,
      templateUrl: templatePath + "rename.html",
      controller: 'RenameCtrl',
      windowClass:'modal-opacity'
      resolve:{
        file: ()->
          file
        scope: ()->
          $scope
      }
    }

  $scope.invite = (document = null) ->
#    console.log CmisService.membershipType
    $scope.isOwner=CmisService.membershipType=='Owner'
    if !$scope.isOwner
      $scope.sendToOwner='Send Request to Room Owner'
    else
      $scope.sendToOwner='Send Invitation Email'
    $scope.sending=false
    $uibModal.open ({
      animation: true,
      templateUrl: templatePath + "invite-model.html",
      controller: "createInviteModal",
      resolve:{
        document:()->
          document
        sendToOwner:()->
          $scope.sendToOwner
        sending:()->
          $scope.sending
        isOwner:()->
          $scope.isOwner
      }
    })
  $scope.updateLeftAsideFolderTree = ()->
    return false
    temperTree = ModelService.tree
    $scope.tree = []
    $timeout(()->
      $scope.$apply()
    ,0)
    $timeout(()->
      $scope.tree = temperTree
    ,0)


  $scope.createFolder = ()->
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "create-folder.html",
      controller: 'CreateFolderCtrl',
      windowClass:'modal-opacity'
    }
    modalInstance.result.then (folderName)->
      if folderName.length==0
        $translate('folder_name_null',).then (text)->
          Utils.warning(text)
        return
      url = CmisServiceSession.defaultRepository.rootFolderUrl+'?objectId='+$scope.currentFolder.id
      postData = {
        'cmisaction': 'createFolder'
        'propertyId[0]':'cmis:name'
        'propertyValue[0]': folderName
        'propertyId[1]' : 'cmis:objectTypeId'
        'propertyValue[1]': 'cmis:folder'
        succinct:true
        includeAllowableActions:true
      }
      $.ajax(
        {
          type: 'POST'
          url:url,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: postData
          success: (object)->
#            $scope.updateLeftAsideFolderTree()
            folder = ModelService.createFolder object
            if !$scope.currentFolder.folderList
              $scope.currentFolder.folderList=[]
            if !$scope.currentFolder.children
              $scope.currentFolder.children=[]
            $scope.currentFolder.folderList.push(folder)
            $scope.currentFolder.children.push(folder)
            $timeout(()->
              $scope.$apply()
            ,0)
            Utils.sendGaEvent "Folder", "Create", folder.id
            folder.createActivity "create-folder", {name:folder.name, to_folder_name:$scope.currentFolder.name}
          error: (r)->
            console.log(r.responseJSON)
            $scope.translateErrorMsg(r.responseJSON,{name:folderName})
        }
      )
  $scope.moveTo = (waitMoveFiles,event)->
    #    ContextMenuService 就是 右键context的 服务 改写了原来的  js 库  把close 方法 放到了ContextMenuService上了 供我们使用
    if(ContextMenuService.menuElement)
      ContextMenuService.close(ContextMenuService.menuElement)
    #    不让他冒泡 选中的文件 就不会 变了
    event.stopPropagation()
#    console.log(files)
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "move-to-folder.html",
      controller: 'moveToFolderModal'
      windowClass:'modal-opacity'
      resolve: {
        files: ()->
          if $scope.multipleChooseFiles.length > 0
            $scope.multipleChooseFiles
          else
            [waitMoveFiles]
        currentFolder: ()->
          $scope.currentFolder
        scope: ()->
          $scope
      }
    }
  $scope.commentContent=''
  $scope.postComment = (content)->
    $scope.choseFile.postComment(content)
    this.commentContent=''

  $scope.openCloudArchive = ()->
    if window.openCloudArchive && typeof window.openCloudArchive == 'function'
      window.openCloudArchive()
  #handle drag and drop a file event.
  $scope.$on 'file-dropzone-drop-event', (event, files)->
    $scope.tempFolder = $scope.currentFolder
    if CmisService.isDrmRoom
      for file in files
        if !Utils.isAllowExtension(file)
          $translate('file_type_error', {allowExtensions:CmisService.allowExtension.join(', ')}).then (text)->
            Utils.warning(text)
          continue
        $scope.openUploadFilePicker($scope.currentFolder, file)
        break
    else
      $scope.upload(files)


  $scope.shareFile = (file)->
#    file.sharedLink='https://www.baidu.com'

#    /api/share/public   post  doc_id
#    g+  https://plus.google.com/share?url=
#    facebook https://www.facebook.com/share.php?u=
#    weibo http://service.weibo.com/share/share.php?url=
#    tweet https://twitter.com/intent/tweet?text=

#    console.log(CmisService)
    $uibModal.open {
      animation: true,
      templateUrl: templatePath + "shared-file-modal.html"
      controller: 'sharedFileModal'
      windowClass:'modal-opacity'
      resolve: {
        scope: ()->
          $scope
        file: ()->
          file
      }
    }
  $scope.fillAndSign = (file,id,event)->
#    console.log 'fillNSign',file
#    console.log CmisService.baseUrl
#    console.log CmisService.baseUrl+'fns/fill-forms-pdf-view?id=1&docId='+file.id
#    console.log window
#    console.log window.top
    if file
      if(file.isDocument())
        if event.data=='openFileFromAchive'
          # only support for fillableform
          console.log(event.data)
          if file.contentStreamMimeType!='application/pdf'
            $translate('not_support_this_type').then (text)->
              Utils.warning(text)
            return false
          else
            docId = file.id
            window.top.postMessage(docId,'*')
        else
          if !Utils.canPreview(file)
            $translate('not_support_this_type').then (text)->
              Utils.warning(text)
            return false
          # pdf 类型 直接传id
          if file.contentStreamMimeType == 'application/pdf'
            docId = file.id
            docUrl = CmisServiceSession.getContentStreamURL(docId, true)
          # 非pdf 类型 看是否转换成功 成功传 rendition streamId 失败提示 不能
  #          console.log(docUrl)
  #          console.log(CmisService.baseUrl+'fns/fill-forms-pdf-view?id=1&docId='+docId)
  #          expect docUrl like https://cloud-docker.connectedpdf.com/cmis/browser/fxcld/root?succinct=true…nt&objectId=f9257948-c852-437c-bfb6-7b5853064634%2C2.0&download=attachment
  #          expect url https://cloud-docker.connectedpdf.com/fns/fill-forms-pdf-view?id=1&docId=f9257948-c852-437c-bfb6-7b5853064634,2.0
            window.top.postMessage(docId,'*')
  #            window.top.location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?fromCloudReading=1&docId='+docId
          else
            file.getRenditions ()->
              if file.renditions
                for rendition,i in file.renditions
                  if rendition.kind == 'smx:converted_pdf' && rendition.length!=0
                    docId = rendition.streamId
                    docUrl = CmisServiceSession.getContentStreamURL(docId, true, {streamId: rendition.streamId})
              if docId
                # expext docUrl https://cloud-docker.connectedpdf.com/cmis/browser/fxcld/root?succinct=true&token=5872fa19e4b07a512a38b3c6%2Cww002%40mailinator.com&streamId=5924fafa-19ba-420f-989c-4dac683d4307%2C1.0-cvtpdf-rdtion&cmisselector=content&objectId=5924fafa-19ba-420f-989c-4dac683d4307%2C1.0-cvtpdf-rdtion&download=attachment
                # expect https://cloud-docker.connectedpdf.com/fns/fill-forms-pdf-view?id=1&docId=5924fafa-19ba-420f-989c-4dac683d4307,1.0-cvtpdf-rdtion
                window.top.postMessage(docId,'*')
  #                window.top.location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?fromCloudReading=1&docId='+docId
              else
                $translate('not_support_this_type').then (text)->
                  Utils.warning(text)
      else
        #  本项目作为 iframe的时候  外部调用 iframe 里面的方法很慢
#        $scope.dbClick(file)
        # 直接 替换hash
        window.location.hash='folder/'+file.id

    else
      $translate('no_file_selected').then (text)->
        Utils.warning(text)
      if id
        # 传id 代表的是 从 fill and sign 页面直接预览 是可以预览的
        location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?&fromCloudReading=1&docId='+id
  window.addEventListener('message', (event)->
    console.log('message')
    console.log(event.data)
    if event.data=='openFileFromFillAndSign' || event.data=='openFileFromAchive'
      if ~event.origin.indexOf(CmisService.baseUrl)
        $scope.fillAndSign(window.CloudReading.choseFile,null,event)
      else
        return
    else
      Utils.warning(event.data)
      return
  )
  window.fillAndSign=$scope.fillAndSign


